package com.cre_drt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;

import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.att.intern.webservice.Incident;
import com.att.intern.webservice.Webservice;
import com.att.intern.webservice.Webservice.TokenInvalidException;

public class IncidentSearchScreen extends ActivityTimeout {

	TextView currentUserString;
	TextView authorizationTypeString;
	TextView buildingInfoField;
	TextView searchResultHelpHint;
	View contentSeparator;
	EditText GEOLOCSearch;
	Button addDamageAssessmentButton;
	ListView incidentList;
	ProgressDialog progressDialog;

	String GEOLOC;
	ArrayList<Incident> listOfIncidents;
	HashMap<String, String> sessionInfo;
	int userInput;
	private Hashtable<Integer, String> glcInfo;

	SessionManager session;
	Webservice searchWebservice;
	InputMethodManager imm;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.incident_search_screen);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("Damage Assessment Reporting");
		actionBar.setSubtitle("Enter GLC to Search");

		session = new SessionManager(getApplicationContext());
		sessionInfo = session.getSessionDetails();

		currentUserString = (TextView) findViewById(R.id.textView1);
		authorizationTypeString = (TextView) findViewById(R.id.textView2);
		buildingInfoField = (TextView) findViewById(R.id.buildingInfoField);
		searchResultHelpHint = (TextView) findViewById(R.id.searchResultHelpHint);
		contentSeparator = (View) findViewById(R.id.contentSeparator);

		currentUserString.append(" " + sessionInfo.get(session.KEY_USERNAME));
		authorizationTypeString.append(" " + sessionInfo.get(session.KEY_AUTHORIZATION));

		progressDialog = new ProgressDialog(this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage("Searching...");
		progressDialog.setCancelable(false);

		GEOLOCSearch = (EditText) findViewById(R.id.geolocSearchTextField);
		incidentList = (ListView) findViewById(R.id.incidentList);
		addDamageAssessmentButton = (Button) findViewById(R.id.addDamageAssessmentButton);

		searchWebservice = new Webservice(getApplicationContext());
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		glcInfo = searchWebservice.getGLCInfo();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.incident_search_screen, menu);
		return true;
	}

	public void startWebService(View view) {
		// Get User Input
		GEOLOC = GEOLOCSearch.getText().toString();

		if (GEOLOC.equals("")) {
			DialogBox errorWindow = new DialogBox("Please enter a valid GEOLOC.", false, getApplicationContext());
			errorWindow.show(getSupportFragmentManager(), "ErrorFragment");
			return;
		} else {
			if (GEOLOC.length() < 5) {
				DialogBox errorWindow = new DialogBox("GEOLOC must be at least 5 digits long.", false, getApplicationContext());
				errorWindow.show(getSupportFragmentManager(), "ErrorFragment");
				return;
			}

			userInput = Integer.valueOf(GEOLOC).intValue();

			// Check if GEOLOC is valid
			if (glcInfo.get(userInput) == null) {
				DialogBox errorWindow = new DialogBox("This is an invalid GEOLOC", false, getApplicationContext());
				errorWindow.show(getSupportFragmentManager(), "ErrorFragment");
				return;
			}

			imm.hideSoftInputFromWindow(GEOLOCSearch.getWindowToken(), 0);

			// Display progress bar
			progressDialog.show();
			new searchGEOLOCAsyncTaskClass().execute();
		}
	}

	private class searchGEOLOCAsyncTaskClass extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			try {
				listOfIncidents = searchWebservice.geolocSearch(sessionInfo.get(session.KEY_SESSION_TOKEN_ID), userInput);
			} catch (TokenInvalidException e) {
				DialogBox invalidTokenWindow = new DialogBox("Invalid TokenID", false, getApplicationContext());
				invalidTokenWindow.show(getSupportFragmentManager(), "ErrorFragment");
				return null;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			progressDialog.dismiss();
			searchByGEOLOC();
		}
	}

	public void searchByGEOLOC() {
		int arrLen = listOfIncidents.size();
		ArrayList<String> statusList = new ArrayList<String>();
		final boolean isIncidentFound;
		
		int GLCInfoLength = glcInfo.get(userInput).length();
		int indexOfThirdTilda = 0;
		int tildaCounter = 0;
		char[] charArray = (glcInfo.get(userInput)).toCharArray();
		
		for (int i = 0; i < GLCInfoLength; i++) {
			if (charArray[i] == '~') {
				indexOfThirdTilda = i;
				tildaCounter++;
			}
			if (tildaCounter == 3) {
				break;
			}
		}
		
		buildingInfoField.setText(glcInfo.get(userInput).substring(10, indexOfThirdTilda) + ", " + glcInfo.get(userInput).substring(0, 2));
				
		if (arrLen == 0) { // No Incidents found
			statusList.add("No Open Incidents Found");
			statusList.add("PM ATTUID: " + glcInfo.get(userInput).substring(3, 9));
			isIncidentFound = false;
			addDamageAssessmentButton.setVisibility(View.VISIBLE);
			addDamageAssessmentButton.setClickable(true);
			searchResultHelpHint.setVisibility(View.INVISIBLE);
			contentSeparator.setVisibility(View.INVISIBLE);
		} else {
			for (int i = 0; i < arrLen; i++) {
				// Put Result Status per Incident in List
				String listItem = listOfIncidents.get(i).getBuildingName() + "\n" +
				 "Event Name: " + listOfIncidents.get(i).getEventName() + "\n" +
					"Status: "	+ listOfIncidents.get(i).getIncidentStatus() + "\n" + 
				 "Record Num: " + listOfIncidents.get(i).getRecNumber() + "\n" + 
		       "Work Req Num: " + listOfIncidents.get(i).getWorkReqNumber();

				statusList.add(listItem);
			}
			isIncidentFound = true;
			addDamageAssessmentButton.setVisibility(View.INVISIBLE);
			addDamageAssessmentButton.setClickable(false);
			searchResultHelpHint.setVisibility(View.VISIBLE);
			contentSeparator.setVisibility(View.VISIBLE);
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, statusList);
		incidentList.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		incidentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
				if (isIncidentFound && listOfIncidents.get(position).getIncidentStatus().equals("Open")) {
					Intent updateDamageAssesmentScreenIntent = new Intent(IncidentSearchScreen.this, UpdateDamageAssessmentScreen.class);
					updateDamageAssesmentScreenIntent.putExtra("incident record num", listOfIncidents.get(position).getRecNumber());
					updateDamageAssesmentScreenIntent.putExtra("geoloc", GEOLOC);
					updateDamageAssesmentScreenIntent.putExtra("geolocResult", glcInfo.get(userInput));
					startActivity(updateDamageAssesmentScreenIntent);
				}
			}
		});
	}

	public void addDamageAssessmentOnClick(View view) {
		Intent addAssesmentIntent = new Intent(this, AddDamageAssessmentScreen.class);
		addAssesmentIntent.putExtra("geoloc", GEOLOC);
		addAssesmentIntent.putExtra("geolocResult", glcInfo.get(userInput));
		startActivity(addAssesmentIntent);
	}
	
	public void bananaHammockLaunch(View view) {
		Intent bananaHammockIntent = new Intent(IncidentSearchScreen.this, BananaHammock.class);
		startActivity(bananaHammockIntent);
	}
}
